package com.zian.task;

import cn.hutool.core.collection.CollUtil;
import com.zian.domain.po.SysOrder;
import com.zian.enums.OrderStatusEnum;
import com.zian.enums.PayStatusEnum;
import com.zian.enums.PayTypeEnum;
import com.zian.service.ISysOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
public class OrderTask {

    private final ISysOrderService orderService;

    @Scheduled(cron = "0 * * * * ?") // 每分钟执行异常
    public void checkAndCancelTimeoutOrders() {
        // 检查并取消超时订单的逻辑

        // 1. 查询出待支付订单，判断是否超时
        List<SysOrder> orders = orderService.lambdaQuery()
                .eq(SysOrder::getOrderStatus, OrderStatusEnum.PENDING_PAYMENT)
                .list();
        // 筛选出超时订单
        List<Long> ids = orders.stream()
                .filter(order -> order.getUpdateTime().plusMinutes(30).isBefore(LocalDateTime.now()))
                .map(SysOrder::getId)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(ids)) return;
        // 2. 修改订单状态为已关闭
        orderService.lambdaUpdate()
                .in(SysOrder::getId, ids)
                .set(SysOrder::getOrderStatus, OrderStatusEnum.TIMEOUT_CLOSED)
                .set(SysOrder::getPayStatus, PayStatusEnum.FAILURE)
                .set(SysOrder::getUpdateTime, LocalDateTime.now())
                .set(SysOrder::getExtraInfo, "订单已关闭，原因：超时未支付")
                .update();

    }

    @Scheduled(cron = "0 0 0 * * ?")  // 每日零点执行
    public void checkAndConfirmOrders() {
        // 检查并确认7天前的订单的逻辑
        // 1. 查询出待支付订单，判断是否超时
        List<SysOrder> orders = orderService.lambdaQuery()
                .eq(SysOrder::getOrderStatus, OrderStatusEnum.GOODS_DELIVERED)
                .list();
        // 筛选出超时订单
        List<Long> ids = orders.stream()
                .filter(order -> order.getUpdateTime().plusDays(7).isBefore(LocalDateTime.now()))
                .map(SysOrder::getId)
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(ids)) return;

        // 2. 修改订单状态为已关闭
        orderService.lambdaUpdate()
                .in(SysOrder::getId, ids)
                .set(SysOrder::getOrderStatus, OrderStatusEnum.TRANSACTION_SUCCESS)
                .set(SysOrder::getUpdateTime, LocalDateTime.now())
                .update();
    }
}
